<template>
  <div style="padding: 15px;">
    <el-form ref="form" :rules="rules" :model="form" label-width="80px">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="来源单号" prop="sourceCode">
              <el-input v-model="form.sourceCode" style="width:75%"  />
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="所属仓库" prop="warehouseCode">
              <warehouseSelect ref="warehouseSelect"  @setWarehouseCode="setWarehouseCode" style="width: 75%"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="入驻商" prop="shipmentCode">
              <shipmentSelect3 ref="shipmentSelect3"  @setShipmentInfo="setShipmentInfo" style="width: 75%"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="承运商">
              <el-select v-model="form.carrierName" filterable placeholder="请选择" clearable style="width:75%" @change="carrierChange">
                <el-option
                  v-for="item in carrierLists"
                  :key="item.code"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="客户" prop="customerCode">
              <customerSelect ref="customerSelect"  @getCustomerCode="getCustomerCode" @relation="relation" style="width: 75%"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="收货人"  prop="receiverName">
              <el-input v-model="form.receiverName"  style="width:75%" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="手机号"  prop="receiverMobile">
              <el-input v-model="form.receiverMobile"  style="width:75%" />
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所在区域" prop="areaList">
            <el-cascader
              v-model="form.areaList"
              :options="parentData.areaOptions"
              :props="{
                value: 'countyName',
                label: 'countyName',
                children: 'children',
              }"
              style="width:75%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="收货地址"  prop="receiverDetailAddress">
              <el-input v-model="form.receiverDetailAddress" style="width:75%"  />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <div class="grid-content bg-purple">
            <el-form-item  label="备注"   prop="remarks">
              <el-input v-model="form.remarks" style="width:88%" />
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="缺货发货">
              <el-switch
                v-model="form.isDeliveringIfStockout"
                :active-value="1" :inactive-value="0">
              </el-switch>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <vxe-toolbar id="toolbar_demo3">
      <template v-slot:buttons>
        <el-button @click="insertEvent">新增明细</el-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      border
      resizable
      show-overflow
      keep-source
      ref="xTable"
      :align="allAlign"
      :data="tableData"
      show-footer
      :footer-method="footerMethod"
      :edit-rules="validRules"
      :edit-config="{trigger: 'click', mode: 'cell'}">
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column field="goodsName" title="商品名称" :edit-render="{name: 'ElSelect'}" width="270">
        <template v-slot:edit="{ row }">
          <goodsSelect  :val2="form.shipmentCode" ref="goodsSelect"  @setGoodsCode="setGoodsCode(row)" />
        </template>
      </vxe-table-column>
      <vxe-table-column field="goodCode" title="商品编码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsBarCode" title="商品条码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsUnitName" title="单位"  :edit-render="{}" width="270">
        <template v-slot:edit="{ row }">
          <el-select v-model="row.goodsUnitName" placeholder="请输入单位" style="width:100%" @change="nameChangeEvent(row)" >
            <el-option
              v-for="item in row.goodsUnitConversionList"
              :key="item.unitName"
              :label="item.unitName"
              :value="item.unitName"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <!-- <vxe-table-column field="goodsUnit" title="单位"  width="270"  :edit-render="{name: '$select', options: units, optionProps: {value: 'code', label: 'unitName'},events: {input: nameChangeEvent}}"></vxe-table-column> -->
      <vxe-table-column field="quantity" title="数量" :edit-render="{name: 'input'}" width="120" ></vxe-table-column>
      <vxe-table-column field="unit" title="单位换算" width="270" ></vxe-table-column>
      <vxe-table-column field="basicUnitName" title="基本单位"   width="120"></vxe-table-column>
      <vxe-table-column field="sumBasicQuantity" title="数量" width="120" >
        <template v-slot="{ row }">
          <span>{{ isNaN(row.unitConvertQuantity * row.quantity)?0:row.unitConvertQuantity * row.quantity}}</span>
        </template>
      </vxe-table-column>
      <vxe-table-column field="remarks" title="备注" :edit-render="{name: 'input'}" width="270"></vxe-table-column>
      <vxe-table-column title="操作" fixed="right" min-width="50">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="删除" placement="top">
            <vxe-button type="text" @click="removeRow(scope.row)">
              <i class="el-icon-delete" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="funcSubmitSave" :disabled="isDisable" plain>保 存</el-button>
      <el-button type="primary" @click="funcSubmitCheck" :disabled="isDisable" plain>提 交</el-button>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'
import VXEUtils from 'vxe-utils'
import { isNumber } from '@/utils/validate.js'
import VXETablePluginElement from 'vxe-table-plugin-element'
import 'vxe-table-plugin-element/dist/style.css'
import goodsSelect from '@/views/components/goodsSaleElSelect.vue'
import supplierSelect from '@/views/components/supplierElSelect.vue'
import {getWarehouse} from '@/api/basicInfo'
import { SelectAddress } from '@/api/orderform';
import { deliveryCheckSubmit, deliverySaveSubmit, carrierList } from '@/api/outStorage'
import shipmentSelect3 from '@/views/components/shipmentSelect3.vue'
import warehouseSelect from '@/views/components/warehouseSelect.vue'
import customerSelect from '@/views/components/customerSelect.vue'
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
VXETable.use(VXETablePluginElement)
export default {
  name: '新增出库单',
  components: {
    goodsSelect,
    warehouseSelect,
    shipmentSelect3,
    customerSelect
  },
  data() {
    return {
      allAlign:'center',
      warehouseData:[],
      carrierLists:[],
      units:[],
      isDisable:false,   //确定键显示按钮
      form: {
        shipmentCode: '',
        type:'',
        warehouseCode:"",
        sourceCode:'',
        customerCode:'',
        remarks: '', // 备注
        isDeliveringIfStockout:0,//缺货发货
        receiverDetailAddress: '', //详细地址
        receiverMobile: '', //手机号
        contacts: '', //收货人
        carrierName: '',
        carrierCode: '', //承运商
        receiverProvince: '',
        receiverCity: '',
        receiverDistrict: '', //省市区
        gmtPlanArrival: '',
        deliveryItemList: []
      },
      parentData: {
        areaOptions: []
      },   //选择区域列表
      loading: false,
      tableData: [
      ],
      rules: {
        shipmentCode: [
          { required: true, message: '请选择入驻商', trigger: 'change' }
        ],
        warehouseCode: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        sourceCode: [
          { pattern:/^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号' },
          { max: 100, message: '数量不能超过100位'}
        ],
        receiverMobile:[
          { pattern:/^[1][0-9]{10}$/, message: '手机号格式不正确' },
        ],
        receiverName: [
          { max: 100, message: '收货人姓名不能超过100位'}
        ],
        receiverDetailAddress: [
          { max: 100, message: '收货地址不能超过100位'}
        ],
        remarks: [
          { max: 180, message: '备注不能超过180位'}
        ],

      },
      validRules: {
        goodsName: [
          { required: true, message: '商品名称必须填写' },
        ],
        goodsUnitName: [
          { required: true, message: '单位必须填写' },
        ],
        quantity: [
          { required: true, message: '数量必须填写' },
          { pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '数量必须大于0' },
          { max: 20, message: '数量不能超过20位'}

        ],
      },
      listQuery: {
        page: 1,
        limit: 13,
        totalzong: 0
      },
    }
  },
  created() {
    SelectAddress().then(response => {
      this.parentData.areaOptions = response.data.records
//       receiverProvince:山东省，
        // receiverCity:临沂市,
        // receiverDistrict:兰山区
    })
  },
  methods: {
    // 选择客户
    getCustomerCode(value) {
      this.form.customerName = value;
    },
    // 递归查找节点路径
    getPathByVal(tree, value, path = []) {
      for (var i = 0; i < tree.length; i++) {
        var tempPath = [...path]
        tempPath.push(tree[i].countyName)
        if (tree[i].countyCode == value) {
            return tempPath
        }
        if (tree[i].children) {
          let reuslt = this.getPathByVal(tree[i].children, value, tempPath)
          if (reuslt) return reuslt
        }
      }
    },
    // 地址：
    relation(value){
      this.form.customerCode = value.code
      this.form.receiverDetailAddress = value.receiveAddress
      this.form.receiverMobile = value.receiverMobile
      this.form.receiverName = value.contacts
      this.form.receiverProvince = value.receiverProvince
      this.form.receiverCity = value.receiverCity
      this.form.receiverDistrict = value.receiverDistrict
      this.$set(this.form, 'areaList', this.getPathByVal(this.parentData.areaOptions, value.receiverDistrict))
    },
    // 选择入驻商
    setShipmentInfo(info) {
      this.form.shipmentCode = info.partyCode;
      this.form.shipmentName = info.userName;
      this.tableData = [];
      this.form.carrierName = ''
      this.carrierList(info.partyCode)
      // this.$refs.warehouseSelect.init(this.form.shipmentCode)
    },
    // 选择仓库
    setWarehouseCode(value){
      this.form.warehouseCode = value;
      this.tableData = [];
      // this.form.shipmentCode = '';
      // this.form.shipmentName = '';
      // this.$refs.shipmentSelect3.setSelectValue(this.form.warehouseCode, this.form.shipmentCode);
    },
    carrierList(shipmentCode){
       carrierList(shipmentCode).then(response => {
        this.carrierLists = response.data.records
      })
    },
    carrierChange(value){
      this.form.carrierCode = value.code
      this.form.carrierName = value.name
    },
    //计算基本单位
    nameChangeEvent (row) {
      const sd = row.goodsUnitConversionList.find(i => i.unitName == row.goodsUnitName)
      row.goodsUnit = sd.unitCode
      row.sumBasicQuantity = isNumber(sd.quantity * row.quantity)?sd.quantity * row.quantity:0
      row.unitConvertQuantity = sd.quantity
      row.basicQuantity = sd.quantity
      row.unit = '1' + row.goodsUnitName + '=' + row.unitConvertQuantity + row.basicUnitName
      row.basicQuantity = sd.quantity

    },
    //商品选择
    setGoodsCode(row){
      let obj = this.$refs.goodsSelect.obj
      row.goodsName = obj.name
      row.goodsCode = obj.code
      row.goodCode = obj.goodCode
      row.unitName = obj.unitName
      row.unitCode = obj.unitCode
      row.basicUnitCode = obj.unitCode
      row.basicUnitName = obj.basicUnitName
      row.basicUnit = obj.unitCode
      row.goodsBarCode = obj.barCode
      row.basicUnit = obj.unitCode
      row.basicUnitName = obj.basicUnitName
      row.spec = obj.spec
      row.volume = obj.volume
      row.expirationQuantity = obj.quality
      row.goodsUnitConversionList = obj.goodsUnitConversionList
      if(row.goodsUnitConversionList.length === 1){
        row.goodsUnitName = row.goodsUnitConversionList[0].unitName
        this.nameChangeEvent (row)
      }
    },
    // 删除行
    removeRow(row){
      this.$refs.xTable.remove(row)
      // 刷新合计，避免因为删除操作而导致合计没法捕获数据变化
      this.$refs.xTable.updateFooter()
    },
    // 公共取消
    fatherItemCancel(modelFlag) {
      switch (modelFlag) {
        case 'add':
          this.modelAddFlag = false
          break
        case 'edit':
          this.modelEditFlag = false
          break
        default:
      }
    },
    // 新增
    insertEvent () {
      if (this.form.shipmentCode) {
        const xTable = this.$refs.xTable
        const newRow = {
        }
        xTable.insert().then(({ row }) => xTable.setActiveRow(row))

      } else {
        this.$message.error('入驻商不能为空')
      }

    },

    // 校验是否存在重复商品+单位的数据
    validDuplication(data){
      let validDuplicationMap = new Map();
      let key;
      let flag = true;
      data.forEach((e, index, list)=>{
        key = e.goodsCode + '-' + e.goodsUnit;
        if(validDuplicationMap.has(key)){
          this.$message.error(`商品“${e.goodsName}”存在相同单位的数据，不能保存`);
          flag = false;
          return false;
        }
        validDuplicationMap.set(key, key);
      })
      return flag;
    },

    // 提交
    funcSubmitCheck() {
      this.form.deliveryItemList = this.$refs.xTable.tableData
      let data =JSON.parse(JSON.stringify(this.form))
      data.receiverProvince = data.areaList?data.areaList[0]:''
      data.receiverCity = data.areaList?data.areaList[1]:''
      data.receiverDistrict = data.areaList?data.areaList[2]:''
      delete data.areaList
      if (!this.$refs.xTable.tableData.length) {
        this.$message.error('请新增明细')
      } else {
        this.$refs['form'].validate((valid) => {
          // 校验数据重复
          if(!this.validDuplication(this.form.deliveryItemList)){
            return ;
          }
          if (valid) {
            const errMap = this.$refs.xTable.validate().catch(errMap => errMap)
            this.$refs.xTable.validate((valids) => {
              if(valids){
                this.isDisable = true
                deliveryCheckSubmit(data).then(response => {
                  this.$message({ message: response.msg, type: 'success' })
                  this.$emit('fatherAddMethod')
                  this.isDisable = false
                }).then(() => {
                  this.$eventBus.$emit('refreshList')
                  this.$store.dispatch("tagsView/delView", this.$route);
                  this.$router.push({
                    path: "/wms/delivery"
                  });
                }).catch(() => this.isDisable = false)
              }else {
                return false
              }
            })
          } else {
            return false
          }
        })
      }
    },
    // 保存
    funcSubmitSave() {
      this.form.deliveryItemList = this.$refs.xTable.tableData
      let data =JSON.parse(JSON.stringify(this.form))
      data.receiverProvince = data.areaList?data.areaList[0]:''
      data.receiverCity = data.areaList?data.areaList[1]:''
      data.receiverDistrict = data.areaList?data.areaList[2]:''
      delete data.areaList
      if (!this.$refs.xTable.tableData.length) {
        this.$message.error('请新增明细')
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            // 校验数据重复
            if(!this.validDuplication(this.form.deliveryItemList)){
              return ;
            }

            const errMap = this.$refs.xTable.validate().catch(errMap => errMap)
            this.$refs.xTable.validate((valids) => {
              if(valids){

                this.isDisable = true
                deliverySaveSubmit(data).then(response => {
                  this.$message({ message: response.msg, type: 'success' })
                  this.$emit('fatherAddMethod')
                  this.isDisable = false
                }).then(() => {
                  this.$eventBus.$emit('refreshList')
                  this.$store.dispatch("tagsView/delView", this.$route);
                  this.$router.push({
                    path: "/wms/delivery"
                  });
                }).catch(() => this.isDisable = false)
              }else {
                return false
              }
            })
          } else {
            return false
          }
        })
      }
    },

    // 计算总量
    handleSum(data){
      let count = 0
      data.forEach(row => {
        count += Number(isNaN(row.unitConvertQuantity * row.quantity)?0:row.unitConvertQuantity * row.quantity)
      })
      return count
    },

    footerMethod ({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 1) {
            return '合计'
          }
          if (['quantity'].includes(column.property)) {
              return parseFloat(XEUtils.sum(data, column.property)).toFixed(6)
          }
          if (['sumBasicQuantity'].includes(column.property)) {
            // return `${this.handleSum(data)}`
             return this.handleSum(data).toFixed(6)
          }
          return '-'
        })
      ]
    }
  }
}
</script>
<style lang="scss" scoped>
  .dialog-footer {
    margin: 150px auto;
    width: 175px;
    // float: right;
  }
  .el-select-dropdown__item.selected {
    color: #606266;
    font-weight: 400;
  }
  </style>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
 padding: 6px 0;
}
.vxe-toolbar{padding:0 0 10px 0}
</style>
